<?php

class IRutils {

	static function runSVD($dim) {
		// -d dimensions -o file_root   matrixFile
		$command = "./svd -d $dim -o ./svddata/SVDres ./svddata/termDocMatrix.txt";
		return shell_exec($command);
	}
	//in



	//3
	//x
	//y
	//z

	//s={x,y,z}
	//dim=3;

	static function readS() {
		$s = array();
		$sfile = file('./svddata/SVDres-S', FILE_IGNORE_NEW_LINES);
		foreach ($sfile as $i => $line) { //for all lines
			if ($i==0) {$dim=$line;} // dimensions is on the first line
			else {$s[$i-1]=$line;} // save the lines starting at index 0
		}
		if (count($s) != $dim) { // if dimensions is invalid
			$n=count($s);
			exit("Missmatch dimensions in readS: expected $dim; Got $n");
		}
		//else return s
	
		$diagonalSigmaMatrix = IRutils::strArrayToDiagonalFloatMatrix($s);
		return $diagonalSigmaMatrix;
	}
	
	static function invDiagonalMatrix($m1){
		$r=count($m1);
		for ($i=0;$i< $r;$i++){
			if($m1[$i][$i] != 0){
				$m1[$i][$i]=1.0/$m1[$i][$i];
			}		
		}
		return $m1;
	}

	//Ut is matrix

	//row, col (2,3)
	//x1 y1 z1
	//x2 y2 z2

	static function readV() { //Ut is U transpose
		$V = array();
		$Mfile = file('./svddata/SVDres-Vt', FILE_IGNORE_NEW_LINES);
		foreach ($Mfile as $i => $line) {
			if ($i==0) {$size=explode(' ', $line);$rows=$size[0]; $cols=$size[1];}
			else {
				$V[$i-1] = explode(' ', $line);
				if (count($V[$i-1]) != $cols) { exit('cols mismatch in readVt'); }
			}
		}
		$V  = IRutils::castMatrixToFloat($V);
		return $V;
	}


	//Ut is a array of arrays
	static function readUt() { //Ut is U transpose
		$Ut = array();
		$Mfile = file('./svddata/SVDres-Ut', FILE_IGNORE_NEW_LINES);
		foreach ($Mfile as $i => $line) {
			if ($i==0) {$size=explode(' ', $line);$rows=$size[0]; $cols=$size[1];}
			else {
				$Ut[$i-1] = explode(' ', $line);
				if (count($Ut[$i-1]) != $cols) { exit('cols mismatch in readUt'); }
			}
		}
		$Ut  = IRutils::castMatrixToFloat($Ut);
		return $Ut;
	}
	
	static function castMatrixToFloat($m){
		$rows = count($m);
		$cols = count($m[0]);
		for($i=0; $i < $rows; $i++) {
			for($j=0; $j < $cols; $j++) {
				$m[$i][$j] = (float) $m[$i][$j]; 
			}
		}
		//var_dump($m);	
		return $m;
	}
	
	static function strArrayToDiagonalFloatMatrix($arr){
		$matrix = array();
		$size = count($arr);
		for($i=0; $i < $size; $i++) {
			$matrix[$i] = array();
			for($j=0; $j < $size; $j++) {
				if($i == $j){
					$matrix[$i][$j] = (float) $arr[$i];	
				} else {
					$matrix[$i][$j] = 0;
				}
			} 
		}
		return $matrix;
	}
	
	static function matrixmult($m1,$m2){
		$r=count($m1);
		$c=count($m2[0]);
		$p=count($m2);
		if(count($m1[0])!=$p){throw new Exception('Incompatible matrixes'.$r."x".count($m1[0])."::".$p."x".$c);}
		$m3=array();
		for ($i=0;$i< $r;$i++){
			for($j=0;$j<$c;$j++){
				$m3[$i][$j]=0;
				for($k=0;$k<$p;$k++){
					$m3[$i][$j]+=$m1[$i][$k]*$m2[$k][$j];
				}
			}
		}
		return($m3);
	}

}

?>
